/**
 * Created by lixiaodi on 2018/9/26 0026.
 */
mini.parse();
var websocket;
var openMenu = [];              //显示页签的菜单
//未读消息
$(function () {
    unReadMsg();
});
//页面初始化
$(function () {
	//通过缓存获取用户信息
	var item2 = localStorage.getItem("item");
	var userInfoObj = JSON.parse(item2);
	if(userInfoObj){
		//console.log(userInfoObj,'有');
	}else{
		window.location.href = "/DSMP/ToLogin.do";
	}
	$('#userWelcome2').html(userInfoObj.userCode + '   ');

    // //点击菜单跳转
    // var menu = new Menu("#mainMenu", {
    //     itemclick: function (item) {
    //         if (item.url) {
    //             var url1 = 'formDesign/formTemplate2.html';
    //             var url2 = 'dbShowGrid.html';
    //             var url3 = 'dbShowGrid2.html';
    //
    //
    //             //菜单跳-表单展示/表格
    //             // if(item.url == url1 || item.url == url2) {
    //             if(item.url.indexOf(url1)>-1 || item.url.indexOf(url2)>-1 || item.url.indexOf(url3)>-1) {
    //             	console.log(item,'当前被点击的数据');
    //                 fIt = {item:item,jump:'menu'};
    //                 openMenu.push(fIt);
    //             }else {
    //                 fIt = [];
    //             }
    //
    //             // localStorage.clear();
    //             localStorage.removeItem("formDesignAction");
    //             // localStorage.removeItem("formShow");
    //
    //             //菜单跳-表单设计器
    //             if(item.url.indexOf('formDesign/formDesign4')>-1) {
    //                 menuJump = true;//新增
    //             }else {
    //                 menuJump = false;//编辑
    //             }
    //             activeTab(item);
    //         }
    //     }
    // });
    // $(".sidebar").mCustomScrollbar({ autoHideScrollbar: true });
    // new MenuTip(menu);
    //
    //
    // //var sessionId = $.cookie("sessionId");
    // $.ajax({
    //     url: ajaxUrl + "/index/index.do",
    //     success: function (data) {
    //         var id = mini.get("id");
    //         if(data.userInfo != null && data.userInfo != ''){
    //         	id.setValue(data.userInfo.userId);
    //         	var userInfoId = id.getValue();
    //         	menu.loadData(data.treeDate);
    //         	onWebSocket(userInfoId);
    //         }else{
    //         	window.location.href = "/DSMP/ToLogin.do";
    //         }
    //     },
    //     error:function(){
    //         console.log("失败");
    //     }
    // })
    //
    // //toggle
    // $("#toggle, .sidebar-toggle").click(function () {
    //     $('body').toggleClass('compact');
    //     mini.layout();
    // });
    //
    // //dropdown
    // $(".dropdown-toggle").click(function (event) {
    //     $(this).parent().addClass("open");
    //     return false;
    // });
    //
    // $(document).click(function (event) {
    //     $(".dropdown").removeClass("open");
    // });
    inintall();
});
function inintall() {

    //点击菜单跳转
    var menu = new Menu("#mainMenu", {
        itemclick: function (item) {
            if (item.url) {
                var url1 = 'formDesign/formTemplate2.html';
                var url2 = 'dbShowGrid.html';
                var url3 = 'dbShowGrid2.html';


                //菜单跳-表单展示/表格
                // if(item.url == url1 || item.url == url2) {
                if(item.url.indexOf(url1)>-1 || item.url.indexOf(url2)>-1 || item.url.indexOf(url3)>-1) {
                    console.log(item,'当前被点击的数据');
                    fIt = {item:item,jump:'menu'};
                    openMenu.push(fIt);
                }else {
                    fIt = [];
                }

                // localStorage.clear();
                localStorage.removeItem("formDesignAction");
                // localStorage.removeItem("formShow");

                //菜单跳-表单设计器
                if(item.url.indexOf('formDesign/formDesign4')>-1) {
                    menuJump = true;//新增
                }else {
                    menuJump = false;//编辑
                }
                activeTab(item);
            }
        }
    });
    $(".sidebar").mCustomScrollbar({ autoHideScrollbar: true });
    new MenuTip(menu);


    //var sessionId = $.cookie("sessionId");
    $.ajax({
        url: ajaxUrl + "/index/index.do",
        success: function (data) {
            var id = mini.get("id");
            if(data.userInfo != null && data.userInfo != ''){
                id.setValue(data.userInfo.userId);
                var userInfoId = id.getValue();
                menu.loadData(data.treeDate);
                onWebSocket(userInfoId);
            }else{
                window.location.href = "/DSMP/ToLogin.do";
            }
        },
        error:function(){
            console.log("失败");
        }
    })

    //toggle
    $("#toggle, .sidebar-toggle").click(function () {
        $('body').toggleClass('compact');
        mini.layout();
    });

    //dropdown
    $(".dropdown-toggle").click(function (event) {
        $(this).parent().addClass("open");
        return false;
    });

    $(document).click(function (event) {
        $(".dropdown").removeClass("open");
    });
}
function activeTab(item) {
   var tabs = mini.get("mainTabs");
    var tab = tabs.getTab(item.id);
    if (!tab) {
        tab = { name: item.id, title: item.text, url: item.url, iconCls: item.iconCls, showCloseButton: true,row:item.row,data:item.data };
        tab = tabs.addTab(tab);
    }
    formItem = item;
    tabs.activeTab(tab);
}
var fIt;//菜单跳表单数据
var menuJump = false;


//退出登陆
function signOut(){
    $.ajax({
        url: ajaxUrl + "/loginout.do",
        // url: ajaxUrl + "/ToLogin.do",
        type:"POST",
        success: function (data) {
            window.location.href = "/DSMP/pages/login.html";
            //清空缓存
            localStorage.clear();
            //window.location.replace('/bpm/pages/login.html');
        },
        error:function(){
            console.log("退出登陆失败");
        }
    })
}
//修改密码
function updatePassword(){
	 mini.open({
         targetWindow: window,
         url: "../pages/alertBox/upcatePassword.html",
         title: "修改密码", width: 500, height: 300,
         onload: function () {
        	 //var iframe = this.getIFrameEl();
        	 //var data = { action: "new" };
        	 //iframe.contentWindow.SetData(data);
        	 //window.location.href = "/bpm/ToLogin.do";
         },
         ondestroy: function (action) {
        	 //console.log(action);
        	 if(action == "save"){
                 window.location.href = "/DSMP/pages/login.html";
                 //window.location.href = "/DSMP/ToLogin.do";
                 //清空缓存
                 localStorage.clear();

        	 }
         }
     });
 }
//每1分钟请求一次消息
// setInterval(unReadMsg, 60000);
//未读消息条数
function unReadMsg(){

    $.ajax({
        url: ajaxUrl + '/index/CountMsg.do',
        type: 'POST',
        success: function (data){
            console.log(data);
            var countNum = data.msgNum;
            if(countNum > 0){
                $("#msgNum").text(parseInt(countNum));
                //未读消息条数显示
                $('#msgNum').show();
            }else{
                $('#msgNum').hide();
            }
        },
        error: function (data){
            console.log('请求失败');
        }
    })
}
//用户信息
function findByUserInfo(){
	 mini.open({
         targetWindow: window,
         url: bootPATH + "../frame/frame1/pages/alertBox/userInfo.html",
         title: "用户信息", width: 600, height: 400,
         onload: function () {
             var iframe = this.getIFrameEl();
             var data = { action: "new" };
             iframe.contentWindow.SetData(data);
        	 //window.location.href = "/bpm/ToLogin.do";
         },
         ondestroy: function (action) {
        	 if(action == "ok"){
        		 window.location.href = "/DSMP/ToLogin.do";
        	 }
         }
     });
}

//标签页切换
function activeChanged() {
    var tabs = mini.get("mainTabs");
    var tab = tabs.getActiveTab();
    console.log(tab,'active tab');
    if (tab) {
        tabs.on('activechanged', function (e) {
            reloadTab();//刷新
        })
    }
}
function reloadTab() {
    var tabs = mini.get("mainTabs");
    var tab = tabs.getActiveTab();
    var url1 = 'miniUI/frame/frame1/pages/formLayout/formTable.html';
    var url2 = 'miniUI/frame/frame1//pages/dbShowGrid.html';
    if (tab.url == url1 || tab.url == url2) {
        tabs.reloadTab(tab);
    }
}
//单页面刷新
function  onRefreshClick() {
    var tabs = mini.get('mainTabs');
    var tab = tabs.getActiveTab();

    tabs.reloadTab(tab);
}
//获取当前打开的页签
function mainTab(){
    var tabs = mini.get("mainTabs");
    var nowTab = tabs.getActiveTab();
    return nowTab;
}
//关闭标签页
function removeTab() {
    var tabs = mini.get("mainTabs");
    var tab = tabs.getActiveTab();
    if (tab) {
        tabs.removeTab(tab);
    }
    // tabs.on('beforecloseclick', function (e) {
    //     loadTab(url);
    // })
}

//获取表单跳转数据
function getFormItem() {
    var tabs = mini.get("mainTabs");
    var nowTab = tabs.getActiveTab();
    //判断当前打开的页签是否是鼠标最后一个点击的菜单，如果是值不变，如果不是，值修改
    openMenu.forEach(function (val) {
        if(nowTab.name === val.item.id){
            fIt = {item:val.item,jump:'menu'};
        }
    })
    return fIt;
}

function isMenuJump() {
    return menuJump;
}

function onWebSocket(userInfoId) {
    //判断当前浏览器是否支持WebSocket
    if ('WebSocket' in window) {
        websocket = new WebSocket("ws://"+webSocketUrl+"/MyWebSocket/"+userInfoId);
    }else {
        alert('当前浏览器 Not support websocket')
    }

    //连接发生错误的回调方法
    websocket.onerror = function () {
        setMessageInnerHTML("WebSocket连接发生错误");
    };

    //连接成功建立的回调方法
    websocket.onopen = function () {
        setMessageInnerHTML("WebSocket连接成功");
    }

    //接收到消息的回调方法
    websocket.onmessage = function (event) {
        console.log(event,'onmessage');
        var data = $.parseJSON(event.data);
        var mum = data['socketCount'];
        var msg = data['socketList'];
        //发送人：socketUser     发送时间：socketData
        // 发送消息：socketMessage     未读消息数量：socketCount
        // 所有未读消息集合：socketList
        if(data != null){
            if(parseInt(mum)>0){
                $("#msgNum").show();
                $("#msgNum").text(parseInt(mum));
            }else{
                $("#msgNum").hide();
            }
        }
    }

    //连接关闭的回调方法
    websocket.onclose = function () {
        setMessageInnerHTML("WebSocket连接关闭");
    }

    //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
    window.onbeforeunload = function () {
        closeWebSocket();
    }

    //将消息显示在网页上
    function setMessageInnerHTML(sendMessage) {
        // document.getElementById('message').innerHTML += sendMessage + '<br/>';
        console.log(sendMessage);
    }

    //关闭WebSocket连接
    function signOut(){
    	websocket.close();
        $.ajax({
            url: ajaxUrl + "/loginout.do",
            type:"POST",
            success: function (data) {
                window.location.href = "/bpm/ToLogin.do";
                //window.location.replace('/bpm/pages/login.html');
            },
            error:function(){
                console.log("退出登陆失败");
            }
        })
        
    }

    //发送消息
    function send() {
        var message = document.getElementById('text').value;//要发送的消息内容
        var now=getNowFormatDate();//获取当前时间
        document.getElementById('message').innerHTML += (now+"发送人："+userno+'<br/>'+"---"+message) + '<br/>';
        document.getElementById('message').style.color="red";
        var ToSendUserno=document.getElementById('usernoto').value; //接收人编号：4567
        message=message+"|"+ToSendUserno//将要发送的信息和内容拼起来，以便于服务端知道消息要发给谁
        websocket.send(message);

        var url = "../../bpm/socketUser/insertMessage.do";

        var socketUser = {
            messageRemark : message,
            messageStutas : '1',
            socketUser : userno,
            socketfoUser : ToSendUserno
        };
        //var socketUser = JSON.stringify(su);
        $.ajax({
            type : 'POST',
            url : url,
            data : socketUser,
            success : function(data){
                if(data.message != "success"){
                    mini.alert("提交成功！");
                }
            },
            error : function (message){
                mini.alert("异常抛出");
            }
        })

    }
    //获取当前时间
    function getNowFormatDate() {
        var date = new Date();
        var seperator1 = "-";
        var seperator2 = ":";
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
            + " " + date.getHours() + seperator2 + date.getMinutes()
            + seperator2 + date.getSeconds();
        return currentdate;
    }
}
function meessageList1(){
    var item = {
        iconCls: "fa fa-desktop",
        // id: formId,
        text: "表单展示",
        url: "../pages/message/Messageunread.html"
    };
    parent.activeTab(item);//与父页面通信
}